package xyz.dao;

import android.content.Context;

import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.TypeConverter;
import androidx.room.TypeConverters;

import java.util.Date;

import xyz.entity.Note;

@Database(entities = {Note.class}, version = 1, exportSchema = false)
@TypeConverters({Converters.class})
public abstract class NoteDatabase extends RoomDatabase {
    private static final String DB_NAME = "db_note.db";
    private static volatile NoteDatabase instance;

    private static NoteDatabase create(final Context context) {
        return Room.databaseBuilder(context, NoteDatabase.class, DB_NAME)
                .build();
    }

    public static synchronized NoteDatabase getInstance(Context ctx) {
        if (instance == null) {
            instance = create(ctx);
        }
        return instance;
    }

    public abstract NoteDao getNoteDao();

}

class Converters {
    @TypeConverter
    public static Date fromTimestamp(Long value) {
        return value == null ? null : new Date(value);
    }

    @TypeConverter
    public static Long dateToTimestamp(Date date) {
        return date == null ? null : date.getTime();
    }
}